package controller

import (
	"errors"
	"github.com/balance_foods/common"
	"github.com/balance_foods/global"
	"github.com/balance_foods/middleware"
	"github.com/balance_foods/model/foods"
	"github.com/balance_foods/router"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

const category_prefix = "category"

type CategoryApi struct {
}

func init() {

	category := CategoryApi{}

	group := router.Router.Group(category_prefix, middleware.Cors())

	{
		group.POST("edit", middleware.JWTAuthMiddleware(), category.edit)
		group.POST("list", middleware.JWTAuthMiddleware(), category.list)

	}
}

func (CategoryApi) edit(ctx *gin.Context) {

	categoryRequest := foods.CategoryRequest{}

	err := ctx.ShouldBindJSON(&categoryRequest)
	if err != nil {
		common.FailWithErr(err, ctx)
		return
	}

	id := categoryRequest.Id

	var category foods.Category

	category.Id = id

	if id > 0 {
		err = global.Db.First(&category).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			common.FailWithErr(err, ctx)
			return
		}
	}
	category.Name = categoryRequest.Name
	category.Hot = categoryRequest.Hot
	category.Image = categoryRequest.Image
	global.Db.Save(&category)
	common.SuccessWithMessage("操作成功", ctx)
	return
}

func (CategoryApi) list(ctx *gin.Context) {

	pageRequest := common.PageRequest{}

	err := ctx.ShouldBindJSON(&pageRequest)

	if err != nil {
		common.FailWithErr(err, ctx)
		return
	}

	page := pageRequest.Page

	pageSize := pageRequest.PageSize

	offset := page * pageSize

	var list []foods.Category

	global.Db.Model(&foods.Category{}).Offset(offset).Limit(pageSize).Find(&list)

	if list == nil {
		list = []foods.Category{}
	}

	pageResponse := common.PageResponse{}

	pageResponse.PageRequest = pageRequest

	pageResponse.List = list

	common.SuccessWithData(pageResponse, ctx)

	return

}
